package chances.wechat.model;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import chances.wechat.entity.WechatStbBind;
import chances.wechat.entity.WechatUser;

public class WeixinSession {

	private static final long serialVersionUID = 1L;

	private List<WechatStbBind> bindStbs = new ArrayList<WechatStbBind>();

	private String nickname;

	private WechatUser weixinUser;
	
	private String icon;
	
	private String openId;

	public String getIcon() {
		if(weixinUser!=null){
		return weixinUser.getAvator();
		}else{
			return icon;
		}
	}
	
	public void setIcon(String icon){
		this.icon = icon;
	}

	private String deviceId;

	private String backPath;

	public WechatUser getWeixinUser() {
		return weixinUser;
	}

	public void setWeixinUser(WechatUser weixinUser) {
		this.weixinUser = weixinUser;
	}

	public WeixinSession() {
		this.openId = WeixinSession.createGuestId();
	}

	public static String createGuestId() {
		return "guest_" + System.currentTimeMillis();
	}

	public boolean isBind() {
		return this.bindStbs.size() > 0;
	}

	public boolean isGuest() {
		String userId = this.openId;
		if (userId != null) {
			return userId.startsWith("guest");
		} else {
			return true;
		}

	}

	public List<WechatStbBind> getBindStbs() {
		return bindStbs;
	}

	public void setBindStbs(List<WechatStbBind> bindStbs) {
		this.bindStbs = bindStbs;
	}

	public String getNickname() {
		if(weixinUser != null){
			try {
				return URLDecoder.decode(weixinUser.getNickname(), "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getDeviceId() {
		return deviceId;
	}

	public void setDeviceId(String deviceId) {
		this.deviceId = deviceId;
	}

	public String getBackPath() {
		return backPath;
	}

	public void setBackPath(String backPath) {
		this.backPath = backPath;
	}
	
	public static void saveNewBind(WeixinSession weixinSession, WechatStbBind bind) {
		List<WechatStbBind> bindStbs = weixinSession.getBindStbs();
		bindStbs.add(bind);
		
	}

	public String getOpenId() {
		return openId;
	}

}
